package com.ctcemti.mdm.project.sys.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.ctcemti.mdm.common.result.Result;
import com.ctcemti.mdm.common.result.ResultUtil;
import com.ctcemti.mdm.common.util.*;
import com.ctcemti.mdm.project.sys.dao.CompanyMapper;
import com.ctcemti.mdm.project.sys.dao.InfDisciplinesMapper;
import com.ctcemti.mdm.project.sys.dao.OrgStationMapper;
import com.ctcemti.mdm.project.sys.dao.ProjectMapper;
import com.ctcemti.mdm.project.sys.entity.*;
import com.ctcemti.mdm.project.sys.entity.formdata.BaseReq;
import com.ctcemti.mdm.project.sys.service.ICompanyService;
import com.ctcemti.mdm.project.sys.service.IOrgStationService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

/**
 * @ClassName IOrgStationService
 * @Description 工点逻辑处理类
 * @Author bxf
 * @Date 16:02 2019/8/8
 * @Version V1.0
 **/
@Service
@Slf4j
public class OrgStationServiceImpl implements IOrgStationService {

    @Autowired
    private OrgStationMapper orgStationMapper;
    @Value("${ctcemti.errorfilepath}")
    private String errorfilepath;
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private InfDisciplinesMapper infDisciplinesMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private CommonService commonService;
    @Autowired
    private ICompanyService companyService;

    @Autowired
    RedisUtil redisUtil;
    /**
     * @Author bxf
     * @Description 根据主键删除
     * @Date 11:38 2019/7/12
     * @Param
     * @return
     **/
    @Override
    @Transactional
    public int deleteByPrimaryKey(Integer id){
        return orgStationMapper.deleteByPrimaryKey(id);
    }
    /**
     * @Author bxf
     * @Description 插入项目工点
     * @Date 11:39 2019/7/12
     * @Param
     * @return
     **/
    @Override
    @Transactional
    public int insert(OrgStation record){
        return orgStationMapper.insert(record);
    }

    /**
     * @Author bxf
     * @Description 选择性字段插入
     * @Date 11:39 2019/7/12
     * @Param
     * @return
     **/
    @Override
    @Transactional
    public int insertSelective(OrgStation record){
        return orgStationMapper.insertSelective(record);
    }
    /**
     * @Author bxf
     * @Description 根据主键获取
     * @Date 11:40 2019/7/12
     * @Param
     * @return
     **/
    @Override
    public OrgStation selectByPrimaryKey(String id){
        return orgStationMapper.selectByPrimaryKey(id);
    }
    /**
     * @Author bxf
     * @Description
     * @Date 11:41 2019/7/12
     * @Param 根据主键选择性字段更新对象
     * @return
     **/
    @Override
    @Transactional
    public int updateByIdSelective(OrgStation orgStation){
        return orgStationMapper.updateByPidSelective(orgStation);
    }
    /**
     * @Author bxf
     * @Description
     * @Date 11:47 2019/7/12
     * @Param 根据主键更新对象
     * @return
     **/
    @Override
    @Transactional
    public int updateByPrimaryKey(OrgStation record){
        return orgStationMapper.updateByPrimaryKey(record);
    }

    /**
     * @Author bxf
     * @Description 获取所有数据字典字典分类表子目
     * @Date 10:55 2019/7/15
     * @Param
     * @return
     **/
    @Override
    public List<OrgStation> selectAllOrgStation(){
        return orgStationMapper.selectAll();
    }

    /**
     * @Author bxf
     * @Description 根据父id获取对象list
     * @Date 16:18 2019/7/12
     * @Param
     * @return
     **/
    @Override
    public List<OrgStation> selectByPid(String s){

        Example example = new Example(OrgStation.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("projectId",s);
        return orgStationMapper.selectByExample(example);

    }

    /**
     * @Author bxf
     * @Description 根据实体中的属性值进行查询，查询条件使用等号
     * @Date 15:19 2019/7/16
     * @Param orgStation
     * @return
     **/
    @Override
    public List<Map<String,Object>> selectOrgStation(OrgStation orgStation){
        return orgStationMapper.selectMapByEntity(orgStation);
    }

    /**
     * @Author bxf
     * @Description 根据主键批量删除
     * @Date 11:38 2019/7/12
     * @Param ids
     * @return
     **/
    @Override
    @Transactional
    public int deleteByPrimaryKeys(String ids){
        return orgStationMapper.deleteByPrimaryKeys(Arrays.asList(ids.split(",")));
    }
    /**
     * @Author bxf
     * @Description 根据id分页获取数据
     * @Date 8:04 2019/7/18
     * @Param
     * @return
     **/
    @Override
    public PageInfo<Map<String,Object>> selectListByPid(String id , BaseReq baseReq){
        PageHelper.startPage(baseReq.getPageIndex(),baseReq.getPageSize(),"org.sort");
        OrgStation orgStation = new OrgStation();
        orgStation.setProjectId(id);
        List<Map<String,Object>> list = orgStationMapper.selectAllListByProjectId(orgStation);
        return new PageInfo<Map<String,Object>>(list);
    }

    @Transactional
    @Override
    public Map<String, Object> uploadFile(MultipartFile multipartFile, String projectId, HttpServletResponse response,HttpServletRequest request) throws SQLException, IOException {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        OrgProject project = projectMapper.selectByPrimaryKey(projectId);//获取项目
        InfDisciplines infDisciplines = new InfDisciplines();
        infDisciplines.setPid(Integer.valueOf(project.getCategory()));
        List<InfDisciplines> infDisciplinesList = infDisciplinesMapper.select(infDisciplines);
        //ExcelImportResult<OrgStation> excelImportResult = ExcelParseUtils.importExcelMore(multipartFile,0,1,OrgStation.class,new ExcelVerifyHandlerForOrgstation(orgStationMapper,infDisciplinesList));
        ExcelImportResult<OrgStation> excelImportResult = ExcelParseUtils.importExcelMore(multipartFile,0,1,OrgStation.class,null);
        boolean flag = true;
        if(excelImportResult==null){
            resultMap.put("flag",flag);
        }else if(excelImportResult.getFailList().size()>0){//验证失败，重新写入excel，并保存
            String filename = UUID.randomUUID().toString();//获取新的文件名
            File folder = new File(errorfilepath);//文件夹
            if(!folder.exists()){
                boolean mkFlag = folder.mkdirs();
                if (mkFlag) {
                    log.error("未找到上传文件夹，新建文件夹");
                }
            }
            FileOutputStream fos = null;
            try {
                //fileOutputStream = new FileOutputStream(file);
                //excelImportResult.getWorkbook().write(fileOutputStream);
                List<OrgStation> slist = excelImportResult.getList();//获取所有成功项
                List<OrgStation> flist = excelImportResult.getFailList();//获取所有失败项
                slist.addAll(flist);
                Collections.sort(slist);
                ExportParams exportParams = new ExportParams(null,null,"错误列表");
                exportParams.setStyle(ExcelExportStylerImpl.class);
                Workbook workbook = ExcelExportUtil.exportExcel(exportParams,OrgStation.class, slist);
                fos = new FileOutputStream(errorfilepath+"/"+filename+".xls");
                workbook.write(fos);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                if(fos!=null){
                    fos.close();
                }
            }
            flag = false;
            resultMap.put("flag",flag);
            resultMap.put("filecode",filename);

        }else{//成功验证，准备导入数据
            List<OrgStation> list = excelImportResult.getList();
            String loginId = JWTUtil.getLoginId(request.getHeader("Authorization"));
            List<String> codelist = new ArrayList<String>();//归集编号查询id
            Map<String,Object> tempmap = new HashMap<String,Object>();
            for(InfDisciplines infDisciplineslist:infDisciplinesList){
                tempmap.put(infDisciplineslist.getName(),infDisciplineslist.getId()+"");
            }
            for(OrgStation orgStation:list){
                String type = tempmap.get(orgStation.getType())==null?"1":String.valueOf(tempmap.get(orgStation.getType()));
                orgStation.setType(type);
                orgStation.setProjectId(projectId);
                orgStation.setModifiedBy(loginId);
                orgStation.setModifyDate(new Date());
                orgStation.setId(UUID.randomUUID().toString());
            }
            //项目工点插入
            BatchOperationUtils<OrgStation> batchOperationUtils = new BatchOperationUtils();
            batchOperationUtils.batchOperation(list, 200,var->orgStationMapper.insertBatch(var));
            resultMap.put("flag",flag);
        }
        return resultMap;
    }

    @Override
    public Result getProjectsForTree(String pId, String type, String personId) {
        List<TreeObject> result = new ArrayList<>();
        //从redis中根据人员id获取对应的所有组织
        List<OrgOrganization> orgOrganizationsForSelected = new ArrayList<>();
        orgOrganizationsForSelected = (List<OrgOrganization>) redisUtil.get(personId);
        if(orgOrganizationsForSelected == null || orgOrganizationsForSelected.size() == 0){
            //插入关系
            commonService.insertComRelationToRedisByPersonId(personId);
        }
        orgOrganizationsForSelected = (List<OrgOrganization>) redisUtil.get(personId);
        //判断父节点的类型
        switch(type){
            //公司
            case "1":
                for(OrgOrganization t:orgOrganizationsForSelected){
                    if (t.getParentId() != null && t.getParentId().equals(pId)) {
                        //判断类型
                        //虚拟组织
                        if (t.getType().equals(3)) {
                            String count = companyMapper.countCompany(t.getId());
                            String countPro = companyMapper.countProject(t.getId());
                            //如果公司下面虚拟组织包含项目
                            if(Integer.parseInt(countPro)>0){
                                TreeObject treeProject = new TreeObject();
                                treeProject = setTreeObjectFromOrg(treeProject, t);
                                result.add(treeProject);
                            }
                            //如果公司下面虚拟组织包含公司
                            if (Integer.parseInt(count) > 0) {
                                TreeObject treeProject = new TreeObject();
                                treeProject = setTreeObjectFromOrg(treeProject, t);
                                result.add(treeProject);
                            }
                        }
//                        if (t.getType().equals(3)) {
//                            String count = companyMapper.countProject(t.getId());
//                            if (Integer.parseInt(count) > 0) {
//                                TreeObject treeProject = new TreeObject();
//                                treeProject = setTreeObjectFromOrg(treeProject, t);
//                                result.add(treeProject);
//                            }
//                        }
                        //公司
                        if (t.getType().equals(1)) {
                            //获取虚拟组织，判断虚拟组织是否有项目，如果有加入result中
                            TreeObject treeProject = new TreeObject();
                            treeProject = setTreeObjectFromOrg(treeProject, t);
                            result.add(treeProject);
                        }
                    }
                }
                break;
            //虚拟组织
            case "3":
                for(OrgOrganization t:orgOrganizationsForSelected){
                    if(t.getParentId()!=null && t.getParentId().equals(pId)){
                        TreeObject treeProject = new TreeObject();
                        treeProject = setTreeObjectFromOrg(treeProject,t);
                        result.add(treeProject);
                    }
                }
                break;
            //项目部
            case "4":
                //根据pId获取该项目是否为总项目
                boolean ifPrimaryProject = false;
                OrgProject o = new OrgProject();
                o.setOrgId(pId);
                List<OrgProject> checkIfParentProject = projectMapper.select(o);
                if(checkIfParentProject == null || checkIfParentProject.size() ==0){
                    return ResultUtil.success();
                }
                //循环判断
                for(OrgProject tp:checkIfParentProject){
                    if(tp.getPrjId()==null || tp.getPrjId().equals("")){
                        ifPrimaryProject = true;
                        break;
                    }
                }
                //根据不同类型的项目获取
                if(ifPrimaryProject){
                    //如果是总项目。只获取总项目
                    for(OrgProject tp:checkIfParentProject){
                        if(tp.getPrjId() == null || tp.getPrjId().equals("")){
                            TreeObject primaryPro = new TreeObject();
                            primaryPro = setTreeObjectFromPro(primaryPro,tp,true);
                            result.add(primaryPro);
                            continue;
                        }
                    }
                }else{
                    //如果不是总项目，添加所有项目
                    for(OrgProject tp:checkIfParentProject){
                        TreeObject ordinaryPro = new TreeObject();
                        ordinaryPro = setTreeObjectFromPro(ordinaryPro,tp,true);
                        result.add(ordinaryPro);
                    }
                }
                break;
            //如果点击的是项目
            case "5":
                //根据总项目获取子项目或获取不到值
                OrgProject p = new OrgProject();
                p.setPrjId(pId);
                List<OrgProject> list = projectMapper.select(p);
                //获取工点
                Example example = new Example(OrgStation.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("projectId",pId);
                example.orderBy("sort");

                List<OrgStation> orglist = orgStationMapper.selectByExample(example);
                for(OrgStation pTemp:orglist){
                    TreeObject treeObject = new TreeObject();
                    treeObject = setTreeObjectFromStation(treeObject,pTemp,false);
                    result.add(treeObject);
                }
                if(list == null || list.size() ==0){
                    return ResultUtil.success(result);
                }
                for(OrgProject pTemp:list){
                    TreeObject treeObject = new TreeObject();
                    treeObject = setTreeObjectFromPro(treeObject,pTemp,true);
                    result.add(treeObject);
                }
                break;
        }
        return ResultUtil.success(result);
    }

    @Override
    @Transactional
    public int moveOrgStation(String ids, String projectId,HttpServletRequest request) {
        String loginId = JWTUtil.getLoginId(request.getHeader("Authorization"));
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("projectId",projectId);
        param.put("ids",Arrays.asList(ids.split(",")));
        param.put("modifiedBy",loginId);
        param.put("modifyDate",DateUtil.formatDate(new Date(),"yyyy-MM-dd hh:mm:ss"));
        return orgStationMapper.moveOrgStation(param);
    }

    @Override
    public Result getProjectsForTreeByName(HttpServletRequest request,String id, String type,String name,String stationFlag) {
        String personId = JWTUtil.getLoginId(request.getHeader("Authorization"));
        String loginName = JWTUtil.getLoginName(request.getHeader("Authorization"));
        List<TreeObject> result = new ArrayList<>();
        //从redis中根据人员id获取对应的所有组织
        List<OrgOrganization> orgOrganizationsForSelected = new ArrayList<>();
        orgOrganizationsForSelected = (List<OrgOrganization>) redisUtil.get(personId);
        if(orgOrganizationsForSelected == null || orgOrganizationsForSelected.size() < 1){
            //插入关系
            if("Administrator".equals(loginName)){
                commonService.insertComRelationToRedisByPersonIdForAdministrator(personId);
            }else{
                commonService.insertComRelationToRedisByPersonId(personId);
            }
        }
        //commonService.insertComRelationToRedisByPersonId(personId);
        List<OrgOrganization> orglist_temp = new ArrayList<OrgOrganization>();
        orgOrganizationsForSelected = (List<OrgOrganization>) redisUtil.get(personId);

        List<String> temp = new ArrayList<String>();
        List<String> idtemp = new ArrayList<String>();//用于存放需要删除的项目id
        List<String> orgprojecttemp = new ArrayList<String>();
        for(OrgOrganization orgOrganization:orgOrganizationsForSelected){
            temp.add(orgOrganization.getId());
        }
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("shortName",name);
        param.put("type",type);
        List<Map<String, Object>> list = orgStationMapper.optimizeSelectPrevStationByName(param);
        for(Map<String, Object> resultmap:list){
            if(!temp.contains(String.valueOf(resultmap.get("id"))) && "4".equals(String.valueOf(resultmap.get("id")))){
                idtemp.add(String.valueOf(resultmap.get("id")));
            }
        }
        Map<String,Object> param1 = new HashMap<String,Object>();
        param1.put("ids",idtemp);
        List<String> idtemps = new ArrayList<String>();//用于存放需要删除的项目id
        if(idtemp.size()>0){
            List<Map<String, Object>> nextmaps = orgStationMapper.optimizeSelectNextStationById(param1);
            for(Map<String, Object> resultmap:nextmaps){
                idtemps.add(String.valueOf(resultmap.get("id")));
            }
        }

        List<Map<String,Object>> resultList = new ArrayList<Map<String,Object>>();
        for(Map<String, Object> resultmap:list){
            if(!temp.contains(String.valueOf(resultmap.get("id"))) && Integer.valueOf(String.valueOf(resultmap.get("type")))<4){
                resultList.add(resultmap);
            }else{
                resultList.add(resultmap);
            }
        }
        for(int i=0;i<resultList.size();i++){
            if(idtemps.contains(String.valueOf(resultList.get(i).get("id")))){
                resultList.remove(i);
            }
        }

        return ResultUtil.success(resultList);
    }



    public Result getProjectsForTreeByName1(HttpServletRequest request,String id, String type,String name,String stationFlag) {
        String personId = JWTUtil.getLoginId(request.getHeader("Authorization"));
        String loginName = JWTUtil.getLoginName(request.getHeader("Authorization"));
        List<TreeObject> result = new ArrayList<>();
        //从redis中根据人员id获取对应的所有组织
        List<OrgOrganization> orgOrganizationsForSelected = new ArrayList<>();
        orgOrganizationsForSelected = (List<OrgOrganization>) redisUtil.get(personId);
        if(orgOrganizationsForSelected == null || orgOrganizationsForSelected.size() < 1){
            //插入关系
            if("Administrator".equals(loginName)){
                commonService.insertComRelationToRedisByPersonIdForAdministrator(personId);
            }else{
                commonService.insertComRelationToRedisByPersonId(personId);
            }
        }
        //commonService.insertComRelationToRedisByPersonId(personId);
        List<OrgOrganization> orglist_temp = new ArrayList<OrgOrganization>();
        orgOrganizationsForSelected = (List<OrgOrganization>) redisUtil.get(personId);
        if("Administrator".equals(loginName)){
            Result<List<OrgOrganization>> result1 = companyService.getByPersonIdForAdministrator(request);
            orglist_temp = result1.getData();//获取顶端代码
        }else{
            Result<List<OrgOrganization>> result1 = companyService.getByPersonId(personId);//获取所有顶端对象
            orglist_temp = result1.getData();//获取顶端代码
        }

        Map<String,Object> param1 = new HashMap<String, Object>();
        List<String> orgParentId = new ArrayList<String>();
        List<String> orgId = new ArrayList<String>();
        List<String> orgidlist = new ArrayList<String>();
        List<String> orgidlistDown = new ArrayList<String>();
        if(!StringUtil.isEmpty(orglist_temp.get(0).getParentId())){
            for (OrgOrganization orgOrganization:orglist_temp){
                orgParentId.add(orgOrganization.getParentId());
                orgId.add(orgOrganization.getId());
            }
            param1.put("orgParentId",orgParentId);
            param1.put("orgId",orgId);
            orgidlist = orgStationMapper.selectOrgByProjectId(param1);
            orgidlistDown = orgStationMapper.selectOrgDownByProjectId(param1);
        }

        List<String> temp = new ArrayList<String>();
        List<String> orgprojecttemp = new ArrayList<String>();
        for(OrgOrganization orgOrganization:orgOrganizationsForSelected){
            temp.add(orgOrganization.getId());
        }

        //获取符合条件的项
        Map<String,Object> params = new HashMap<String, Object>();
        params.put("name",name);
        params.put("stationFlag",stationFlag);
        List<Map<String,Object>> result1 = orgStationMapper.selectAllOrgstationByName(params);
        List<String> idtemp = new ArrayList<String>();
        for(Map<String,Object> map:result1){
            String id_temp = String.valueOf(map.get("id"));
            if(temp.contains(id_temp) && !idtemp.contains(id_temp)){
                idtemp.add(id_temp);
            }
        }
        if(idtemp.size()<1){
            return ResultUtil.success(result);
        }
        params.put("ids",idtemp);
        List<Map<String,Object>> list = orgStationMapper.selectOrgstationByIds(params);
        params.put("type",5);//5代表项目
        List<Map<String,Object>> projectlist = orgStationMapper.selectOrgstationByIds(params);//获取项目


        for(Map<String,Object> mapresult:list){
            if(!"5".equals(String.valueOf(mapresult.get("type"))) && !"9".equals(String.valueOf(mapresult.get("type")))){
                TreeObject treeObject = new TreeObject();
                TreeObject treeObjectResult = setTreeObjectFromMap(treeObject,mapresult,true);
                if(temp.contains(String.valueOf(mapresult.get("id"))) && orgidlistDown.contains(String.valueOf(mapresult.get("id")))){
                    if (treeObjectResult.getType().equals(3)) {

                        String count = companyMapper.countCompany(treeObjectResult.getId());
                        String countPro = companyMapper.countProject(treeObjectResult.getId());
                        //如果公司下面虚拟组织包含项目
                        if(Integer.parseInt(countPro)>0){
                            result.add(treeObjectResult);
                            orgprojecttemp.add(String.valueOf(mapresult.get("id")));//获取所有组织
                        }
                        //如果公司下面虚拟组织包含公司
                        if (Integer.parseInt(count) > 0) {
                            result.add(treeObjectResult);
                            orgprojecttemp.add(String.valueOf(mapresult.get("id")));//获取所有组织
                        }
                    }else{
                        result.add(treeObjectResult);
                        orgprojecttemp.add(String.valueOf(mapresult.get("id")));//获取所有组织
                    }
                }
            }
        }
//        for(int i=0;i<result.size();i++){
//            TreeObject treeObject = result.get(i);
//            if(!StringUtil.isEmpty(treeObject.getId()) && !orgprojecttemp.contains(treeObject.getId())){
//                result.remove(i);
//            }
//        }
        List<String> projectList = new ArrayList<String>();
        for (int j=0;j<projectlist.size();j++){
            for(Map<String,Object> map:projectlist){
                OrgProject o = new OrgProject();
                o.setOrgId(String.valueOf(map.get("id")));
                List<OrgProject> checkIfParentProject = projectMapper.select(o);
                OrgProject project = projectMapper.selectByPrimaryKey(String.valueOf(map.get("id")));//获取当前对应的project
                if(checkIfParentProject.size()>0){//是总项目
                    TreeObject treeObject = new TreeObject();
                    TreeObject treeObjectResult = setTreeObjectFromMap(treeObject,map,true);
                    if(orgprojecttemp.contains(String.valueOf(map.get("parent_id"))) && checkRepeat(treeObjectResult,result)){
                        result.add(treeObjectResult);
                        orgprojecttemp.add(treeObjectResult.getId());
                    }

                }else if(String.valueOf(map.get("parent_id")).equals(project.getPrjId())){//是所属项目
                    TreeObject treeObject = new TreeObject();
                    TreeObject treeObjectResult = setTreeObjectFromMap(treeObject,map,true);
                    if(orgprojecttemp.contains(String.valueOf(map.get("parent_id"))) && checkRepeat(treeObjectResult,result)){
                        result.add(treeObjectResult);
                        orgprojecttemp.add(treeObjectResult.getId());
                    }
                }else if(String.valueOf(map.get("parent_id")).equals(project.getOrgId())){//所属组织
                    boolean ifPrimaryProject = true;
                    for(Map<String,Object> map1:projectlist){
                        if(!StringUtil.isEmpty(project.getPrjId()) && project.getId().equals(String.valueOf(map1.get("id"))) && project.getPrjId().equals(String.valueOf(map1.get("parent_id")))){
                            OrgProject orgproject = projectMapper.selectByPrimaryKey(String.valueOf(map1.get("parent_id")));//获取当前对应的project
                            if(orgproject.getOrgId().equals(project.getOrgId())){
                                TreeObject treeObject = new TreeObject();
                                TreeObject treeObjectResult = setTreeObjectFromMap(treeObject,map1,true);
                                if(orgprojecttemp.contains(String.valueOf(map1.get("parent_id"))) && checkRepeat(treeObjectResult,result)){
                                    result.add(treeObjectResult);
                                    orgprojecttemp.add(treeObjectResult.getId());
                                }
                                ifPrimaryProject = false;
                            }
                        }
                    }
                    if(ifPrimaryProject){
                        TreeObject treeObject = new TreeObject();
                        TreeObject treeObjectResult = setTreeObjectFromMap(treeObject,map,true);
                        if(orgprojecttemp.contains(String.valueOf(map.get("parent_id"))) && checkRepeat(treeObjectResult,result)){
                            result.add(treeObjectResult);
                            orgprojecttemp.add(treeObjectResult.getId());
                        }
                    }
                }
            }
        }
        if("1".equals(stationFlag)){
            for(Map<String,Object> mapresult:list){
                if("9".equals(String.valueOf(mapresult.get("type")))){//9为工点
                    TreeObject treeObject = new TreeObject();
                    TreeObject treeObjectResult = setTreeObjectFromMap(treeObject,mapresult,false);
                    if(orgprojecttemp.contains(String.valueOf(mapresult.get("parent_id")))){
                        result.add(treeObjectResult);
                    }
                }
            }
        }

        return ResultUtil.success(result);
    }

    private boolean checkRepeat(TreeObject treeObjectResult,List<TreeObject> result){
        boolean flag = true;
        for(TreeObject treeObject:result){
            if(treeObjectResult.getId().equals(treeObject.getId()) && treeObjectResult.getPId().equals(treeObject.getPId())){
                flag = false;
                break;
            }
        }
        return  flag;
    }
    private TreeObject setTreeObjectFromOrg(TreeObject treeObject,OrgOrganization organization){
        treeObject.setId(organization.getId());
        treeObject.setPId(organization.getParentId());
        treeObject.setName(organization.getName());
        treeObject.setShortName(organization.getShortName());
        treeObject.setType(organization.getType());
        treeObject.setParent(true);
        return treeObject;
    }

    private TreeObject setTreeObjectFromPro(TreeObject treeObject,OrgProject orgProject,boolean ifPriPro){
        treeObject.setId(orgProject.getId());
        treeObject.setPId(orgProject.getPrjId());
        treeObject.setName(orgProject.getName());
        treeObject.setShortName(orgProject.getShortName());
        treeObject.setParent(ifPriPro);
        treeObject.setType(5);
        treeObject.setCategory(orgProject.getCategory());//获取项目类别
        return treeObject;
    }
    private TreeObject setTreeObjectFromStation(TreeObject treeObject,OrgStation orgStation,boolean ifPriOrg){
        treeObject.setId(orgStation.getId());
        treeObject.setPId(orgStation.getProjectId());
        treeObject.setName(orgStation.getName());
        treeObject.setShortName("");
        treeObject.setParent(ifPriOrg);
        treeObject.setType(9);//工点类型标记
        return treeObject;
    }
    private TreeObject setTreeObjectFromMap(TreeObject treeObject,Map<String,Object> map,boolean ifPriOrg){
        treeObject.setId(String.valueOf(map.get("id")));
        treeObject.setPId(String.valueOf(map.get("parent_id")));
        treeObject.setName(String.valueOf(map.get("name")));
        treeObject.setShortName(String.valueOf(map.get("shortName")));
        treeObject.setParent(ifPriOrg);
        treeObject.setType(Integer.valueOf(String.valueOf(map.get("type"))));
        return treeObject;
    }
}
